package cn.lisens.listener;

import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class CustomHttpSessionListener implements HttpSessionListener {

	private static final Logger logger = LoggerFactory.getLogger(CustomHttpSessionListener.class);
    private final AtomicInteger sessionCount = new AtomicInteger(0);

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        int count = sessionCount.incrementAndGet();
        HttpSession session = se.getSession();
        
        logger.info("Session创建: ID={}, 当前会话数: {}", session.getId(), count);
        logger.info("Session超时时间: {}分钟", session.getMaxInactiveInterval() / 60);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        int count = sessionCount.decrementAndGet();
        HttpSession session = se.getSession();
        
        logger.info("Session销毁: ID={}, 剩余会话数: {}", session.getId(), count);
        
        // 记录会话时长
        long creationTime = session.getCreationTime();
        long duration = System.currentTimeMillis() - creationTime;
        logger.info("会话时长: {}秒", duration / 1000);
    }
    
    public int getActiveSessionCount() {
        return sessionCount.get();
    }
}
